<?php

namespace App\Tools;

use Illuminate\Support\Facades\DB;

use function dump;

class SQL
{
    /**
     * @var array
     */
    protected static $sqlList = [];

    /**
     * @var int
     */
    protected static $maxCacheSqlCount = 100;

    /**
     * @var string
     */
    protected static $lastSql;

    /**
     * 启动SQL监听器.
     */
    public static function dump(): void
    {
        DB::listen(function ($query): void {
            $singleSql = $query->sql;
            if ($query->bindings) {
                foreach ($query->bindings as $replace) {
                    $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
                    $singleSql = preg_replace('/\?/', $value, $singleSql, 1);
                }
            }

            static::push($singleSql);

            dump($singleSql);
        });
    }

    /**
     * @param string $sql
     */
    private static function push($sql): void
    {
        self::$sqlList[] = $sql;
        array_splice(self::$sqlList, 0, -self::$maxCacheSqlCount);
        self::$lastSql = end(self::$sqlList);
    }
}
